//
//  DownloadCellTableViewCell.m
//  MHO
//
//  Created by papo on 4/12/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "DownloadCellTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "Lib.h"

@interface DownloadCellTableViewCell()
@property (nonatomic, strong) NSTimer* timer;

@end

@implementation DownloadCellTableViewCell

- (void)awakeFromNib
{
    // Initialization code
    self.iconImage.layer.masksToBounds = YES;
    self.iconImage.layer.cornerRadius = 4;

    [self.progressBar setProgress:0 animated:NO];
//    [self.progressBar setProgressImage:[[UIImage imageNamed:@"proget_bar.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 1, 0, 1) ]];
//    [self.progressBar setTrackImage:[UIImage imageNamed:@"bg_proget_bar.png"]];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

+ (DownloadCellTableViewCell*)cellFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:@"DownloadCellTableViewCell" owner:self options:nil] objectAtIndex:0];
}

- (void)setDownload:(TCBlobDownloader *)download {
    _download = download;
    Application* app = _download.app;
    if (!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(update) userInfo:nil repeats:YES];
    }
    [self.iconImage setImageWithURL:[Contants getImageUrl:app.imagePath width:100 height:100]];
    if (self.iconImage.image) {
    }
    self.appName.text = app.appName;
    
    if (!_download.isExecuting || !_download.delegate) {
        [_pauseButton setImage:[UIImage imageNamed:@"icon_play_download_main.png"] forState:0];
        _statusLb.text = @"Tạm dừng";
    }
    
    [self updateData];
}

- (void)update {
    if (self.download == nil || self.download.isExecuting == NO) {
        return;
    }
    [self updateData];
}

- (void)updateData {
    float receivedSize = (float)(self.download.receivedDataLength + _download.firstDataLength) / 1024 / 1024;
    float expectedSize = (float)self.download.expectedDataLength / 1024 / 1024;
    float totalSize = (float)_download.totalDataLength / 1024 / 1024;
    
    // fix
    //    receivedSize = totalSize - expectedSize;
    float percent = receivedSize / totalSize;
    
    if (_download.isFinished && percent >= 1) {
        [self.timer invalidate];
        self.percentLb.text = @"100%";
        self.totalSizeLb.text = [NSString stringWithFormat:@"%0.f/%0.fMB", totalSize, totalSize];
        [self.progressBar setProgress:1.0 animated:YES];
        [_pauseButton setImage:[UIImage imageNamed:@"icon_redownload_main.png"] forState:UIControlStateNormal];
        self.statusLb.text = @"Đã tải xong";
        
        [[DownloadManager sharedManager] saveDownload:_download finish:YES];
        return;
    }
    
    if (_download.isCancelled) {
        self.statusLb.text = @"Bị lỗi";
        [_pauseButton setImage:[UIImage imageNamed:@"icon_redownload_main.png"] forState:UIControlStateNormal];
    }
    if (percent > 1) {
        percent = 1;
        receivedSize = totalSize;
    }
    [self.progressBar setProgress:percent animated:YES];
    self.percentLb.text = [NSString stringWithFormat:@"%0.f %%",round(percent * 100)];
    self.totalSizeLb.text = [NSString stringWithFormat:@"%0.f/%0.fMB", receivedSize, totalSize];
}

- (IBAction)startPauseRetryButtonPressed:(id)sender {
    if (_download.isExecuting) {
        [_download cancelDownloadAndRemoveFile:NO];
        [[[DownloadManager sharedManager] listDownload] removeObject:self.download];
//        _download = nil;
        [self.pauseButton setImage:[UIImage imageNamed:@"icon_play_download_main.png"] forState:UIControlStateNormal];
        self.statusLb.text = @"Tạm dừng";
    }
    else  {
        [self.pauseButton setImage:[UIImage imageNamed:@"icon_pause_download_main.png"] forState:UIControlStateNormal];
        TCBlobDownloader* download = [DownloadManager startDownload:_download.app];
        if (download)
        {
            _download = download;//[[[DownloadManager sharedManager] listDownload] lastObject];
            self.statusLb.text = @"Đang tải";
        }
        else {
            self.statusLb.text = @"Bị lỗi";
            [self.pauseButton setImage:[UIImage imageNamed:@"icon_redownload_main.png"] forState:UIControlStateNormal];
        }
    }
}

- (IBAction)deleteDownload:(id)sender {
    if (self.download) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn có muốn xoá game đang tải không?" cancelButtonTitle:@"Có" otherButtonTitles:@[@"Không"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [[DownloadManager sharedManager] removeDownload:self.download];
            }
        }];
    }
}
@end
